package com.zhkj.txg.module.home.ui

import android.content.Context
import android.content.Intent
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.txg.R
import com.zhkj.txg.module.home.adapter.CateProductAdapter
import com.zhkj.txg.module.home.adapter.CateSortAdapter
import com.zhkj.txg.module.home.adapter.SortCallback
import com.zhkj.txg.module.home.entity.CateSortUIEntity
import com.zhkj.txg.module.home.vm.CategoryViewModel
import com.zhkj.txg.module.product.popup.ProductSharePopupWindow
import com.zhkj.txg.module.product.ui.ProductDetailActivity2
import com.zhkj.txg.module.product.ui.ProductShareActivity
import com.zhkj.txg.module.product.ui.ShareFriendActivity
import com.zhkj.txg.utils.ConfigManager
import com.zhkj.txg.utils.ShareUtils
import kotlinx.android.synthetic.main.activity_category_detail.*

class ProductListActivity : ViewModelActivity<CategoryViewModel>() {

    companion object {
        private val CAT_ID = "id"
        private val TITLE = "title"
        private val SHOP_ID = "shopId"
        private val TYPE = "type"
        private val SEARCH = "search"
        private val SHOP_CAT_ID = "shopCatId"

        // 从平台分类页打开
        fun categoryOpen(context: Context, title: String, id: Int) {
            val intent = Intent(context, ProductListActivity::class.java)
                .putExtra(CAT_ID, id).putExtra(TITLE, title)
            context.startActivity(intent)
        }  // 从平台分类页打开

        fun categoryOpen(context: Context, title: String, id: Int, shopId: Int) {
            val intent = Intent(context, ProductListActivity::class.java)
                .putExtra(SHOP_ID, shopId).putExtra(CAT_ID, id).putExtra(TITLE, title)
            context.startActivity(intent)
        }

        fun searchOpen(context: Context, title: String, search: String, shopId: Int) {
            val intent = Intent(context, ProductListActivity::class.java)
                .putExtra(SHOP_ID, shopId).putExtra(SEARCH, search).putExtra(TITLE, title)
            context.startActivity(intent)
        }

        // 超市打开
        fun marketOpen(context: Context, title: String, id: Int) {
            val intent = Intent(context, ProductListActivity::class.java)
                .putExtra(CAT_ID, id).putExtra(TITLE, title).putExtra(TYPE, 1)
            context.startActivity(intent)
        }

        // 店铺打开
        fun shopOpen(context: Context, title: String, shopId: Int, shopCatId: Int) {
            val intent = Intent(context, ProductListActivity::class.java)
                .putExtra(SHOP_ID, shopId).putExtra(TITLE, title).putExtra(TYPE, 0)
                .putExtra(SHOP_CAT_ID, shopCatId)
            context.startActivity(intent)
        }

        // 尖货打开
        fun topOpen(context: Context, title: String, catId: Int) {
            val intent = Intent(context, ProductListActivity::class.java)
                .putExtra(CAT_ID, catId).putExtra(TITLE, title).putExtra(TYPE, 2)
            context.startActivity(intent)
        }
    }

    override fun statusTitleBar(): View? = titleCategory
    override fun setViewModel(): CategoryViewModel = createViewModel()
    override val layoutResId: Int = R.layout.activity_category_detail

    private val sortAdapter = CateSortAdapter().apply {
        sortCallback = object : SortCallback {
            override fun sort(sort: CateSortUIEntity) {
                search(sort, true)
            }
        }
    }
    private val productAdapter = CateProductAdapter().apply {
        loadMoreModule?.isEnableLoadMore = true
        loadMoreModule?.setOnLoadMoreListener {
            search(sortAdapter.getSelectSort(), false)
        }
        setOnItemChildClickListener { _, view, position ->
            val product = data[position]
            when (view.id) {
                // 打开店铺
//                R.id.tvCateProductShopName ->
//                    if (product.shopId > 0) ShopActivity.open(
//                        this@ProductListActivity,
//                        product.shopName,
//                        product.shopId
//                    )
//                // 发圈素材
//                R.id.tvCateProductTagMatter -> ShareFriendActivity.open(
//                    this@ProductListActivity,
//                    product.shareContent ?: "", product.shareImages?.toTypedArray() ?: emptyArray()
//                )
//                // 分享赚钱
//                R.id.tvCateProductTagShareEarn -> {
//                    with(sharePopupWindow) {
//                        setShareEarn(if (product.shareEarn.isNullOrEmpty()) "0.0" else product.shareEarn)
//                        productName = product.goodsName
//                        productPrice = product.price
//                        productImage = mutableListOf(product.image)
//                        goodsId = product.id.toLong()
//                        shareUrl = product.shareUrl
//                        showPopupWindow()
//                    }
//                }
            }
        }
    }
    private val sharePopupWindow: ProductSharePopupWindow by lazy {
        ProductSharePopupWindow(this) { type ->
            when (type) {
                2 -> {
                    if (sharePopupWindow.productImage.isNotEmpty()) ProductShareActivity.open(
                        this, sharePopupWindow.goodsId,
                        sharePopupWindow.productImage.toTypedArray(),
                        sharePopupWindow.productName,
                        sharePopupWindow.productPrice
                    ) else toast(getString(R.string.empty_gallery))
                }
                1 -> ShareUtils.shareUrl2Friends(
                    this,
                    ConfigManager.getProductShareContent() ?: "",
                    sharePopupWindow.productName,
                    sharePopupWindow.productImage[0],
                    sharePopupWindow.shareUrl
                )
                else -> ShareUtils.shareUrl2Friends(
                    this,
                    ConfigManager.getProductShareContent() ?: "",
                    sharePopupWindow.productName,
                    sharePopupWindow.productImage[0],
                    sharePopupWindow.shareUrl,
                    true
                )
            }
        }
    }

    override fun initUI() {
        with(rvCateSort) {
            layoutManager = GridLayoutManager(this@ProductListActivity, 3)
            adapter = sortAdapter
        }
        with(rvCategory) {
            layoutManager = LinearLayoutManager(this@ProductListActivity)
            adapter = productAdapter
        }
        // 设置列表空布局
        productAdapter.setEmptyView(R.layout.layout_empty_data)
        productAdapter.setOnItemClickListener { _, _, position ->
            val entity = productAdapter.data[position]
            ProductDetailActivity2.normalProduct(this, entity.id, shopId = intent.getIntExtra(SHOP_ID, 0))
        }
        // 设置标题
        val title = intent.getStringExtra(TITLE)
        titleCategory.setTitleTextContent(title)
        // 设置排序条件
        sortAdapter.setNewData(
            mutableListOf(
                CateSortUIEntity(getString(R.string.composite), "weigh"),
                CateSortUIEntity(getString(R.string.sale), "sales_sum",true),
                CateSortUIEntity(getString(R.string.price), "price", true)
            )
        )
        refreshCategory.setOnRefreshListener {
            search(sortAdapter.getSelectSort(), true)
        }
    }

    override fun initData() {
        val shopId = intent.getIntExtra(SHOP_ID, 0)
        search(sortAdapter.data[0], true)
    }

    override fun initViewModel() {
        viewModel.productListLiveData.observe(this, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    // 判断加载状态
                    if (!it.loadMore) refreshCategory.finishRefresh()
                    else if (it.hasMore) productAdapter.loadMoreModule?.loadMoreComplete()
                    else productAdapter.loadMoreModule?.loadMoreEnd()
                    // 数据填充
                    if (it.loadMore) productAdapter.addData(it.data)
                    else productAdapter.setNewData(it.data)
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                    if (viewModel.page > 1) productAdapter.loadMoreModule?.loadMoreFail()
                    else refreshCategory.finishRefresh(false)
                }
            }
        })
        viewModel.shareInfoLiveData.observe(this, Observer { response ->
            // 打开发圈素材页面
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let {
                ShareFriendActivity.open(this, it.shareContent ?: "", it.shareImages.toTypedArray())
            }
        })
    }

    private fun search(item: CateSortUIEntity, restart: Boolean) {

//        fun searchProduct(
//            token: String, shopId: Int, catId: Int, shopCatId: Int, sort: String,
//            asc: Boolean, type: Int, searchKey: String, restart: Boolean = false
//        ) {
//        viewModel.searchProduct(
//            AccountManager.getToken(), intent.getIntExtra(SHOP_ID, 0),
//            intent.getIntExtra(CAT_ID, 0), intent.getIntExtra(SHOP_CAT_ID, 0),
//            item.type, item.canSort && item.sortAsc, intent.getIntExtra(TYPE, 0),
//            intent.getStringExtra(SEARCH) ?: "", restart
//        )

//        fun searchProduct(
//            token: String, shopId: Int, activeType: Int = 0, search: String, catId: Int, sort: String,
//            sortAsc: Boolean = false, recommend: Int, restart: Boolean = false
//        )

        viewModel.searchProduct(
            token = AccountManager.getToken(),
            shopId =  intent.getIntExtra(SHOP_ID, 0),
            activeType = null,
            search = intent.getStringExtra(SEARCH) ?: "",
            catId = intent.getIntExtra(CAT_ID, 0),
            sort = item.type,
            sortAsc = item.canSort && item.sortAsc,
            recommend = null,
            restart = restart
        )


    }
}